<?php

class Admin_IndexController extends Common_Controller_Admin {

    public function init() {
        parent::init();
    }

    public function indexAction() {

        parent::indexAction();
        $this->redirect('/admin/index/content');
    }

    public function useraddAction() {

        $itemModel = new Application_Model_Users();
        $form = $itemModel->getForm();
        unset($form->login
                ->disabled);
        $form->login
                ->addValidator('notEmpty', false, array());

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                $t = $itemModel->insert(array(
                    'login' => $data['login'],
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'created' => date("Y-m-d H:i:s"),
                    'password' => md5(Zend_Registry::get('staticSalt') . $data['password']),
                        ));
            }
        }

        $this->view->form = $form;
    }

    public function usereditAction() {
        $itemModel = new Application_Model_Users();
        $item = $itemModel->getById($this->getParam('id', 0));
        $form = $itemModel->getForm();
        $form->password->setRequired(false);
        $form->login->setRequired(false);

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                $item->active = $data['active'];
                //$item->confirmed = $data['confirmed'];
                //$item->deleted = $data['deleted'];
                //$item->lastLogin = $data['lastLogin'];
                //$item->rola = $data['rola'];
                //$item->login = $data['login'];
                $item->password = md5(Zend_Registry::get('staticSalt') . $data['password']);
                $item->name = $data['name'];
                $item->email = $data['email'];

                $item->save();

                $this->flashMessenger->addMessage('Zapisano.');
                $this->redirect($_SERVER['REQUEST_URI']);
            }
        }

        $form->active->setValue($item->active);
        //$form->confirmed->setValue($item->confirmed);
        // $form->deleted->setValue($item->deleted);
        //$form->lastLogin->setValue($item->lastLogin);
        // $form->rola->setValue($item->rola);
        $form->login->setValue($item->login);
        $form->name->setValue($item->name);
        $form->email->setValue($item->email);

        $this->view->form = $form;

        $this->render('itemadd');
    }

    public function usersAction() {


        $itemsModel = new Application_Model_Users();
        $this->view->wparams = $whereParams = $this->getFilteredParams('filter');
        $this->view->pparams = $orderParams = $this->getFilteredParams('order');

        $paginator = $this->getPaginator(
                $itemsModel->getAdapterPagin(
                        $itemsModel
                                ->buildWhereFromFiltered($whereParams), $itemsModel
                                ->buildOrderFromFiltered($orderParams)
                )
        );

        $this->view->head = 'Użytkownicy';
        $this->view->paginator = $paginator;
    }

    public function contentAction() {

        $itemsModel = new Application_Model_Content();

        $this->view->wparams = $whereParams = $this->getFilteredParams('filter');
        $this->view->pparams = $orderParams = $this->getFilteredParams('order');

        $paginator = $this->getPaginator($itemsModel->getAdapterPagin(
                        $itemsModel->buildWhereFromFiltered($whereParams), $itemsModel->buildOrderFromFiltered($orderParams)
                ));
        $this->view->paginator = $paginator;
        $this->view->head = "Treści";
        $this->view->addUrl = $this->view->url(array('module' => 'admin', 'action' => 'contentadd',), null, true);
    }

    public function getcmslistAction() {
        $this->noOut();

        $pages = array();

        $content = new Application_Model_Content();
        $pages = $content->getCmsList();

        echo $this->json(array(
            'status' => 'ok',
            'pages' => $pages,
        ));
    }

    public function editCmsFilesAction() {

        $this->addJsFile('markitup/jquery.markitup.js');
        $this->addJsFile('markitup/sets/default/set.js');
        $this->addCssFile('markitup/skins/markitup/style.css');
        $this->addCssFile('markitup/sets/default/style.css');


        $files = array(
        );



        $this->view->files = $files;
    }

    public function categoriesAction() {

        $itemsModel = new Application_Model_Categories();

        $this->view->wparams = $whereParams = $this->getFilteredParams('filter');
        $this->view->pparams = $orderParams = $this->getFilteredParams('order');


        $paginator = $this->getPaginator($itemsModel->getAdapterPagin(
                        $itemsModel->buildWhereFromFiltered($whereParams), $itemsModel->buildOrderFromFiltered($orderParams)
                ));
        $this->view->paginator = $paginator;
        $this->view->head = "Kategorie";
        $this->view->addUrl = $this->view->url(array('module' => 'admin', 'action' => 'categoryadd',), null, true);

        if (isset($whereParams['parentId'])) {

            $p = array();
            $p = $itemsModel->getToHome($whereParams['parentId'], $p);
            $path = array();

            foreach ($p as $pathItem) {
                $path[] = array(
                    'link' => $this->view->url(array('module' => 'admin', 'action' => 'categories', 'filterparentId' => $pathItem['id']), null, true),
                    'label' => $pathItem['title'],
                );
            }
            $path[] = array(
                'link' => $this->view->url(array('module' => 'admin', 'action' => 'categories', 'filterparentId' => '0'), null, true),
                'label' => 'Home',
            );
            $this->view->pathItems = array_reverse($path);
        }
    }

    public function categoryaddAction() {

        $itemModel = new Application_Model_Categories();
        $form = $itemModel->getForm(array());

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {
                $name = preg_replace(array(
                    '#[^a-z0-9\s]+#',
                    '#[\s]+#'
                        ), array(
                    '', '_'
                        ), strtolower($data['title']));

                $t = $itemModel->insert(array(
                    'parentId' => $data['parentId'],
                    'typ' => $data['typ'],
                    'url' => $data['url'],
                    'isHome' => $data['isHome'],
                    'isDefault' => $data['isDefault'],
                    'position' => $data['position'],
                    'title' => $data['title'],
                    'name' => $name,
                    'short' => $data['short'],
                        ));

                $this->redirect('/admin/index/categories');
            }
        }

        $this->view->form = $form;
    }

    public function categoryeditAction() {

        $itemModel = new Application_Model_Categories();
        $item = $itemModel->getById($this->getParam('id', 0));
        $form = $itemModel->getForm(array(
            'id' => $item->id,
                ));

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                $item->parentId = $data['parentId'];
                $item->typ = $data['typ'];
                $item->url = $data['url'];
                $item->isHome = $data['isHome'];
                $item->isDefault = $data['isDefault'];
                $item->position = $data['position'];
                $item->title = $data['title'];
                $item->name = preg_replace(array(
                    '#[^a-z0-9\s]+#',
                    '#[\s]+#'
                        ), array(
                    '', '_'
                        ), strtolower($data['title']));
                $item->short = $data['short'];

                $item->save();

                if (isset($data['submitAndStay'])) {
                    $this->redirect('/admin/index/categoryedit/id/' . $this->getParam('id'));
                } else {
                    $this->redirect('/admin/index/categories');
                }
            }
        }

        $form->parentId->setValue($item->parentId);
        $form->typ->setValue($item->typ);
        $form->url->setValue($item->url);
        $form->isHome->setValue($item->isHome);
        $form->isDefault->setValue($item->isDefault);
        $form->position->setValue($item->position);
        $form->title->setValue($item->title);
        $form->short->setValue($item->short);
        $this->view->form = $form;

        $this->render('categoryadd');
    }

    public function contenteditAction() {

        $itemModel = new Application_Model_Content();
        $catModel = new Application_Model_Categories();
        $catContModel = new Application_Model_ContentCategory();

        $item = $itemModel->getById($this->getParam('id', 0));
        $form = $itemModel->getForm();


        if ($this->_request->isXMLHTTPRequest()) {

            $delete = $this->getParam('delete', 0);
            $add = $this->getParam('add', 0);
            $categoryIdTo = $this->getParam('categoryId', 0);
            if ($delete && $categoryIdTo && $item) {
                $catContModel->deleteRow('contentId=' . $item->id . ' and categoryId=' . $categoryIdTo . '');
            } else if ($add && $categoryIdTo && $item) {
                if ($catContModel->fetchRow('contentId=' . $item->id . ' and categoryId=' . $categoryIdTo . '') == null) {
                    $catContModel->insert(array(
                        'contentId' => $item->id,
                        'categoryId' => $categoryIdTo,
                            )
                    );
                }
            }

            die();
        }



        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                $item->status = $data['status'];
                $item->typ = $data['typ'];
                $item->title = $data['title'];

                $item->meta_keywords = $data['meta_keywords'];
                $item->meta_description = $data['meta_description'];
                $item->meta_robots = $data['meta_robots'];
                $item->isDefault = $data['isDefault'];
                $item->isHome = $data['isHome'];
                $item->position = $data['position'];
                $item->body = $data['body'];
                $item->name = preg_replace(array(
                    '#[^a-z0-9\s]+#',
                    '#[\s]+#'
                        ), array(
                    '', '_'
                        ), strtolower($data['title']));
                $item->short = $data['short'];
                $item->rewrite = strlen($data['rewrite']) < 1 ? $item->name : $data['rewrite'];
                $item->boxName = $data['boxName'];
                $item->boxTag = empty($data['boxTag']) ? '*' : $data['boxTag'];
                $item->userId = $this->getLoggedUserId() == null ? 1 : $this->getLoggedUserId();

                $item->save();

                $currentCats = array_merge($itemModel->getCategories($item->id, true), $data['categoriesSelected']);

                foreach ($currentCats as $cat) {
                    $catcont = $catContModel->fetchRow('contentId=' . $item->id . ' and categoryId=' . $cat);
                    if (!isset($catcont) || empty($catcont)) {
                        $catcont = $catContModel->insert(array(
                            'contentId' => $item->id,
                            'categoryId' => $cat
                                ));
                    }

                    if ($cat == $data['idGlowna']) {
                        $catContModel->db->query('update content_category
                            set isMain=0 
                            where contentId=' . $item->id . ' and categoryId=' . $cat . ' ')->execute();
                        $catcont->isMain = 1;
                        $catcont->save();
                    }
                }

                $itemModel->updateStaticRoutes();
                if (isset($data['submitAndStay'])) {
                    $this->redirect('/admin/index/contentedit/id/' . $this->getParam('id'));
                } else {
                    $this->redirect('/admin/index/content');
                }
            }
        }

        $cats = $catModel->getForOptions('contentId=' . $item->id, null, false);
        $main = $itemModel->getMainCategory($item->id);

        $form->status->setValue($item->status);
        $form->typ->setValue($item->typ);
        $form->title->setValue($item->title);
        $form->meta_keywords->setValue($item->meta_keywords);
        $form->meta_description->setValue($item->meta_description);
        $form->meta_robots->setValue($item->meta_robots);
        $form->isDefault->setValue($item->isDefault);
        $form->isHome->setValue($item->isHome);
        $form->position->setValue($item->position);
        $form->body->setValue($item->body);
        $form->short->setValue($item->short);
        $form->rewrite->setValue($item->rewrite);
        $form->boxName->setValue($item->boxName);
        $form->boxTag->setValue($item->boxTag);
        $form->userId->setValue($item->userId);
        $form->idGlowna->setValue(0);
        $form->idGlowna->setLabel(!$main ? '--nie wybrano--' : $main->title);
        $form->categoriesSelected->addMultiOptions($cats);

        $this->view->form = $form;
    }

    public function contentaddAction() {

        $itemModel = new Application_Model_Content();
        $catModel = new Application_Model_Categories();
        $catContModel = new Application_Model_ContentCategory();
        $form = $itemModel->getForm();

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {
                $name = preg_replace(array(
                    '#[^a-z0-9\s]+#',
                    '#[\s]+#'
                        ), array(
                    '', '_'
                        ), strtolower($data['title']));

                $t = $itemModel->insert(array(
                    'status' => $data['status'],
                    'typ' => $data['typ'],
                    'title' => $data['title'],
                    'meta_keywords' => $data['meta_keywords'],
                    'meta_description' => $data['meta_description'],
                    'meta_robots' => $data['meta_robots'],
                    'isDefault' => $data['isDefault'],
                    'isHome' => $data['isHome'],
                    'name' => $name,
                    'rewrite' => strlen($data['rewrite']) < 1 ? $name : $data['rewrite'],
                    'body' => $data['body'],
                    'short' => $data['short'],
                    'created' => date("Y-m-d H:i:s"),
                    'boxName' => $data['boxName'],
                    'boxTag' => empty($data['boxTag']) ? '*' : $data['boxTag'],
                    'userId' => $this->getLoggedUserId() == null ? 1 : $this->getLoggedUserId(),
                        ));

                $currentCats = array_merge($itemModel->getCategories($t->id, true), $data['categoriesSelected']);

                foreach ($currentCats as $cat) {
                    $catcont = $catContModel->fetchRow('contentId=' . $t->id . ' and categoryId=' . $cat);
                    if (!isset($catcont)) {
                        $catcont = $catContModel->insert(array(
                            'contentId' => $t->id,
                            'categoryId' => $cat
                                ));
                    }

                    if ($cat == $data['idGlowna']) {
                        $catContModel->db->query('update content_category
                            set isMain=0 
                            where contentId=' . $t->id . ' and categoryId=' . $cat . ' ')->execute();
                        $catcont->isMain = 1;
                        $catcont->save();
                    }
                }


                $itemModel->updateStaticRoutes();
                $this->redirect('/admin/index/content');
            }
        }

        $form->removeDisplayGroup('gr-categorie');


        $this->view->form = $form;
    }

    /**
     * 
     * @param string $prefix
     * @return array
     */
    private function getFilteredParams($prefix) {
        $f = array();

        foreach ($this->getAllParams() as $name => $param) {
            if (preg_match('#^' . $prefix . '.*#', $name) == 1)
                $f[preg_replace('#^' . $prefix . '#', '', $name)] = $param;
        }

        return $f;
    }

    public function settingsAction() {
        $itemsModel = new Application_Model_Settings();
        $paginator = $this->getPaginator($itemsModel->getAdapterPagin());
        $this->view->paginator = $paginator;
    }

    public function settingaddAction() {
        $itemModel = new Application_Model_Settings();
        $form = $itemModel->getForm();

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                $t = $itemModel->insert(array(
                    'status' => $data['status'],
                    'active' => $data['active'],
                    'content' => $data['content'],
                    'created' => date("Y-m-d H:i:s"),
                    'userId' => $this->getLoggedUserId() == null ? 1 : $this->getLoggedUserId(),
                        ));
            }
        }

        $this->view->form = $form;
    }

    public function settingeditAction() {
        $itemModel = new Application_Model_Settings();
        $item = $itemModel->getById($this->getParam('id', 0));
        $form = $itemModel->getForm();

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                $item->value = $data['value'];
                $item->save();
            }
        }
        $form->name->setValue($item->name);
        $form->value->setValue($item->value);

        $this->view->form = $form;

        $this->render('settingadd');
    }

    public function logoAction() {
        $form = new Application_Form_Logo();
        $settings = new Application_Model_Settings();

        $conf = $settings->getByName('TITLE');

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($form->isValid($data)) {

                if ($form->image->isUploaded()) {
                    if ($form->image->receive()) {
                        $location = $form->image->getFileName();
                        $newName = preg_replace('#([a-z\s0-9]+)\.([a-z\s0-9]+)$#i', 'logo.$2', $location);
                        $name = explode(DIRECTORY_SEPARATOR, $newName);

                        copy($location, $newName);
                    }
                }

                $conf->value = $data['title'];
                $conf->save();
            }
        }

        $form->title->setValue($conf->value);


        $this->view->form = $form;
    }

}

